package com.letianpai.common.tool;

import java.math.BigDecimal;
import java.util.Random;

/**
 * Created with IntelliJ IDEA.
 * User: Administrator
 * Date: 13-3-27
 * Time: 上午10:03
 * To change this template use File | Settings | File Templates.
 */
public class NumberTool {
    /**
     * 随机得到的4位不等常号,返回这个数组
     */
    public static int[] getFourNumber() {                         //随机得到的6位不等常号
        Random r = new Random();
        int[] a = new int[4];
        for (int i = 0; i < a.length; i++) {
            a[i] = r.nextInt(13) + 1;
            while (isSame(a[i], a, i)) {
                a[i] = r.nextInt(13) + 1;
            }
        }
        return a;
    }

    /**
     * 判定随机生成号码是否重复，返回boolean值
     */
    private static boolean isSame(int i, int[] a, int length) { //判定随机生成号码是否重复
        for (int j = 0; j < length; j++) {
            if (i == 12) return false;
            if (i == a[j]) return true;
        }
        return false;
    }

    /**
     * 对double数据进行取精度.
     * <p/>
     * For example: <br/>
     * double value = 100.345678; <br/>
     * double ret = round(value,4,BigDecimal.ROUND_HALF_UP); <br/>
     * ret为100.3457 <br/>
     *
     * @param value        double数据.
     * @param scale        精度位数(保留的小数位数).
     * @param roundingMode 精度取值方式.
     *                     java.math.BigDecimal.ROUND_UP <br/>
     *                     java.math.BigDecimal.ROUND_DOWN <br/>
     *                     java.math.BigDecimal.ROUND_CEILING <br/>
     *                     java.math.BigDecimal.ROUND_FLOOR <br/>
     *                     java.math.BigDecimal.ROUND_HALF_UP<br/>
     *                     java.math.BigDecimal.ROUND_HALF_DOWN <br/>
     *                     java.math.BigDecimal.ROUND_HALF_EVEN <br/>
     * @return 精度计算后的数据.
     */
    public static double round(double value, int scale, int roundingMode) {
        BigDecimal bd = new BigDecimal(value);
        bd = bd.setScale(scale, roundingMode);
        double d = bd.doubleValue();
        bd = null;
        return d;
    }

    public static double round(double value, int scale) {
        return round(value, scale, BigDecimal.ROUND_HALF_UP);
    }

    //保留小数点(6位)
    public static double retainDecimalPoint(double value) {
        return Double.parseDouble(String.format("%.6f", value));
    }
}
